<?php
/**
 * Created by PhpStorm.
 * User: zhaoye
 * Date: 2017/1/21
 * Time: 下午2:55
 */

namespace ZPHP\Controller;

use ZPHP\Core\Config;
use ZPHP\Core\Factory;

class WSController extends IController{
    protected $socketData;
    protected $fd;
    protected $server;

    public function __construct()
    {
        $this->response = Factory::getInstance(\ZPHP\Network\Websocket\WebResponse::class);
    }

    public function __clone()
    {
        // TODO: Implement __clone() method.
        $cloneArray = ['response'];
        foreach($cloneArray as $item){
            if(!empty($this->$item)){
                $this->$item = clone $this->$item;
            }
        }
    }

    public function setSocket($server, $fd, $socketData){
        $this->server = $server;
        $this->fd = $fd;
        $this->socketData = $socketData;
    }

    /**
     * 处理请求
     * @return \Generator
     */
    public function coroutineStart(){
        $initRes = true;
        if(method_exists($this, 'init')){
            $initRes = yield $this->init();
        }
        if($this->checkResponse() && $initRes){
            $result = yield call_user_func_array($this->coroutineMethod, $this->coroutineParam);
        }
        if($this->checkResponse()){
            if(!is_string($result) && $this->checkApi()){
                $this->jsonReturn($result);
            }else{
                $this->strReturn($result);
            }

        }
        $this->response->finish($this->server, $this->fd);
        $this->destroy();
    }

    public function jsonReturn($data){
        if($this->checkResponse()) {
            $result = json_encode($data);
            if (!empty(Config::get('response_filter'))) {
                $result = $this->strNull($result);
            }
            $this->response->setReponseContent($result);
        }
    }

    public function strReturn($data){
        if($this->checkResponse()) {
            $this->response->setReponseContent(strval($data));
        }
    }

    public function destroy()
    {
        parent::destroy(); // TODO: Change the autogenerated stub
        unset($this->server);
    }

}